import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/video_upload_success_bean.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/smart_home/event/refresh_smart_home_index_event.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:path_provider/path_provider.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

import 'event/refresh_smart_home_category_event.dart';

class SmartHomeUploadService {


  List<SmartHomeUploadItemBean> _uploadList;

  //智能家居门店id
  String _shid;
  BuildContext _context;

  String _defaultStid;
  ///设置值
  SmartHomeUploadService setList(
      List<SmartHomeUploadItemBean> folderList, String shid, String defaultStid) {
    if (folderList == null || folderList.isEmpty) {
      return null;
    }
    _uploadList = folderList;
    _shid = shid;
    _defaultStid = defaultStid;
    return this;
  }


  ///多图上传
  void multiUpload(VgBaseCallback callback)async{
    if (_uploadList == null || _uploadList.isEmpty) {
      callback?.onError("需要上传的数据为空");
      return;
    }
    VgHudUtils.show(AppMain.context, "正在上传");
    try {
      for (SmartHomeUploadItemBean item in _uploadList) {
        item = await _manageFolder(item);
      }
    } catch (e) {
      callback?.onError("处理出现异常");
      print("上传报错:$e");
      return;
    }
    _uploadList.removeWhere((element) => element == null);
    List<Future<SmartHomeUploadItemBean>> futureList = List();
    for (SmartHomeUploadItemBean item in _uploadList) {
      futureList.add(_httpMultiFolder(item, onGetNewFileLength: (value){
        item.folderStorage = value;
      }));
    }
    Future.wait(futureList)
      ..then((List<SmartHomeUploadItemBean> list) {
        List<PicListItemBean> picList = new List();
        list.forEach((element) {
          PicListItemBean picListItemBean = new PicListItemBean(
            picurl: element.netUrl??"",
            type: element.type??"",
            picname: element.folderName??"",
            picsize: element.getSize()??"",
            picstorage: element.getStorage()??"",
            videotime: element.videoDuration??0,
            videopic: element.videoNetCover??"",
            videoid: element.videoid??"",
            sd_video: element?.sdVideo??"",
            sd_storage: element?.sdStorage??"",
            stid: element.getStid()??_defaultStid,
            style: element.style??"99",
            backup: element.backup??"",
          );
          picList.add(picListItemBean);
        });
        String picjson = "";
        if(picList.isNotEmpty){
          picjson = json.encode(picList);
        }
        //接口
        Map<String, dynamic> paramsMap = {
          "authId": UserRepository.getInstance().authId ?? "",
          "shid": _shid ?? null,
          "picjson": picjson ?? "",
        };

        print("准备多图上传测试参数: ${paramsMap}");
        VgHttpUtils.post(NetApi.ADD_STORE_PIC,
            params: paramsMap,
            callback: BaseCallback(onSuccess: (val) {
              callback?.onSuccess(list);
              VgEventBus.global.send(new RefreshSmartHomeIndexEvent());
              VgEventBus.global.send(new RefreshSmartHomeCategoryEvent(id: picList[0]?.stid));
            }, onError: (msg) {
              callback?.onError(msg);
            }));
      }).catchError((e) {
        callback?.onError("上传失败");
      });

  }


  ///处理文件
  Future<SmartHomeUploadItemBean> _manageFolder(
      SmartHomeUploadItemBean item) async {
    if (item == null ||
        item.type == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    if (item.isImage()) {
      return _decodeImage(item);
    }
    if (item.isVideo()) {
      return await _decodeVideo(item);
    }
    return null;
  }

  SmartHomeUploadItemBean _decodeImage(SmartHomeUploadItemBean item) {
    if (item == null ||
        item.type == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }

    File file = File(item.localUrl);
    item.folderStorage = file.lengthSync();

    FileImage image = FileImage(File(item.localUrl));
    if(item.folderWidth == null || item.folderHeight == null){
      // 预先获取图片信息
      image
          .resolve(new ImageConfiguration())
          .addListener(new ImageStreamListener((ImageInfo info, bool _) {
        item.folderWidth = info.image.width;
        item.folderHeight = info.image.height;
        return item;
      }));
    }else{
      return item;
    }

  }

  Future<SmartHomeUploadItemBean> _decodeVideo(
      SmartHomeUploadItemBean item) async {
    if (item == null ||
        item.type == null ||
        StringUtils.isEmpty(item.localUrl)) {
      return null;
    }
    File file = File(item.localUrl);
    Directory rootPath = await getTemporaryDirectory();
    Directory tempDirectory = new Directory('${rootPath.path}/imageTemp');
    if (!tempDirectory.existsSync()) {
      tempDirectory.createSync();
    }
    String tmpVideoCover = await VideoThumbnail.thumbnailFile(
      video: item.localUrl,
      thumbnailPath: tempDirectory?.path,
      imageFormat: ImageFormat.JPEG,
      maxWidth: 1920,
      quality: 100,
    );
    item.videoLocalCover = tmpVideoCover;
    //
    VideoPlayerController videoController = VideoPlayerController.file(file);
    await videoController.initialize();
    item.videoDuration = videoController?.value?.duration?.inSeconds;
    item.folderWidth = videoController?.value?.size?.width?.floor();
    item.folderHeight = videoController?.value?.size?.height?.floor();
    item.folderStorage = file.lengthSync();
    videoController.dispose();
    return item;
  }


  //多图上传
  Future<SmartHomeUploadItemBean> _httpMultiFolder(
      SmartHomeUploadItemBean item, {ValueChanged<int> onGetNewFileLength}) async {
    if (item == null) {
      return null;
    }
    if (item.isImage()) {
      if(StringUtils.isNotEmpty(item.netUrl)){
        return item;
      }
      try {
        item.netUrl = await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.localUrl,
            isNoCompress: false,
            onGetNewFileLength: onGetNewFileLength
        );
        if(StringUtils.isEmpty(item.folderName)){
          item.folderName=item?.getFolderNameStr() ?? "";
        }
        return item;
      } catch (e) {
        print("上传单图异常：$e");
      }
    }

    if (item.isVideo()) {
      try {
        VideoUploadSuccessBean successBean =
        await VgMatisseUploadUtils.uploadSingleVideoForFuture(
            item.localUrl);
        item.netUrl = successBean.url;
        item.videoid = successBean.videoid;
        item.folderName = VgMatisseUploadUtils.getVideoPath();
        if (!StringUtils.isEmpty(successBean.fileSize)) {
          item.folderStorage = int.parse(successBean.fileSize);
        }
        item.sdVideo = successBean.sdVideo;
        item.sdStorage = successBean.sdStorage;
        // if (StringUtils.isEmpty(successBean.coverUrl)) {
        item.videoNetCover =
        await VgMatisseUploadUtils.uploadSingleImageForFuture(
            item.videoLocalCover,
            isNoCompress: false);
        // } else {
        //   item.videoNetCover = successBean.coverUrl;
        // }
        return item;
      } catch (e) {
        print("MediaLibraryIndexService上传异常：$e");
      }
    }
    return null;
  }
}

class PicListItemBean{
  //视频、图片路径
  String picurl;
  String linkpic;
  //01 图片 02 视频
  String type;
  //视频、图片名称
  String picname;
  //视频、图片尺寸
  String picsize;
  //图片、视频大小
  String picstorage;
  //视频时长
  int videotime;
  //视频封面图
  String videopic;
  //视频id
  String videoid;
  String sd_video;
  String sd_storage;
  String stid; //智家空间分类id
  String scid; //智家空间栏目id
  String style;//风格 00现代简约 01中式现代 02美式田园 03美式经典 04欧式豪华 05北欧极简 06日式 07地中海 08潮流混搭 09轻奢 99其他
  String backup;//备注
  String sysmid;//音乐id
  String picid;

  String getCoverUrl(){
    if("01" == type){
      return picurl;
    }
    if("02" == type){
      return videopic;
    }
    if("03" == type){
      return linkpic;
    }
    return picurl;
  }

  PicListItemBean({this.picurl, this.linkpic, this.type, this.picname, this.picsize,
    this.picstorage, this.videotime, this.videopic, this.videoid, this.sysmid,
    this.sd_video, this.sd_storage, this.stid, this.scid, this.style, this.backup, this.picid});

  Map toJson() => {
    "picurl": picurl,
    "linkpic": linkpic,
    "type": type,
    "picname": picname,
    "picsize": picsize,
    "picstorage": picstorage,
    "videotime": videotime,
    "videopic": videopic,
    "videoid": videoid,
    "sd_video": sd_video,
    "sd_storage": sd_storage,
    "scid": scid??"",
    "stid": stid??"",
    "style": style,
    "backup": backup??"",
    "sysmid": sysmid,
    "picid": picid,
  };

}

class SmartHomeUploadItemBean {
  //文件名称
  String folderName;
  String backup; //备注
  String picsize; //视频、图片尺寸
  String picstorage; //图片、视频大小
  //网络
  String netUrl;
  String linkCover;
  String localUrl;
  String shid; //智能家居门店id
  String sfid; //动态id
  String stid; //智家空间分类id
  String scid; //智家栏目id
  String style;//风格 00现代简约 01中式现代 02美式田园 03美式经典 04欧式豪华 05北欧极简 06日式 07地中海 08潮流混搭 09轻奢 99其他
  String stidName;//智家空间分类名
  String scidName;//智家栏目名
  String styleName;//智家风格名
  String type;//01图片 02视频
  String videotime;//视频时长
  //视频封面
  String videoNetCover;
  String videoLocalCover;
  //hd视频信息
  String sdVideo;
  String sdStorage;

  String videoid;
  int videoDuration;
  int folderWidth;
  int folderHeight;
  //文件内存大小
  int folderStorage;
  String picid;
  String linkUrl;
  int sortIndex;
  bool selectStatus = false;
  String sysmid;

  String getStyleName(){
    if(StringUtils.isNotEmpty(styleName)){
      return styleName;
    }
    if(StringUtils.isNotEmpty(style)){
      String tempStyle = ConstantRepository.of().getStyleNameByStyle(style);
      if("未知风格" != tempStyle){
        return tempStyle;
      }
    }
    return "";

  }

  String getPicid(){
    if(StringUtils.isNotEmpty(picid)){
      return picid;
    }
    return "add";
  }

  String getPicUrl(){
    if(is3DLink()){
      return linkUrl;
    }
    return netUrl;
  }

  String getScid(){
    if(StringUtils.isEmpty(scid)){
      return "";
    }
    return scid;
  }


  String getStid(){
    if(StringUtils.isEmpty(stid)){
      return null;
    }
    return stid;
  }


  String getLocalClipPicUrl() {
    if (isImage()) {
      if (!localUrl.contains(".jpg")) {
        return localUrl + ".jpg";
      }
      return localUrl;
    }
    if (isVideo()) {
      return videoLocalCover;
    }
    return localUrl;
  }

  String getLocalPicUrl() {
    if (isImage()) {
      if (StringUtils.isNotEmpty(netUrl) && StringUtils.isEmpty(localUrl)) {
        return netUrl;
      } else {
        return localUrl;
      }
    }
    if (isVideo()) {
      if (StringUtils.isNotEmpty(videoNetCover) && StringUtils.isEmpty(videoLocalCover)) {
        return videoNetCover;
      }
      return videoLocalCover;
    }
    if(is3DLink()){
      if (StringUtils.isNotEmpty(linkCover)){
        return linkCover;
      }
    }
    return localUrl;
  }

  String getPicOrVideoUrl() {
      if (StringUtils.isNotEmpty(netUrl) && StringUtils.isEmpty(localUrl)) {
        return netUrl;
      } else {
        return localUrl;
      }
  }

  String getFolderNameStr() {
    String url = netUrl;
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    List<String> list = url.split("/");
    if (list == null || list.isEmpty) {
      return null;
    }
    return list.elementAt(list.length - 1);
  }

  String getSize() {
    if (folderWidth == null || folderHeight == null) {
      return null;
    }
    return "$folderWidth*$folderHeight";
  }

  String getStorage() {
    if(StringUtils.isNotEmpty(picstorage)){
      return picstorage;
    }
    if (folderStorage == null) {
      return null;
    }
    return (folderStorage / 1024).floor().toString();
  }

  String getSDStorage() {
    if (StringUtils.isEmpty(sdStorage)) {
      return null;
    }
    return sdStorage;
  }

  bool isImage() {
    return type == "01";
  }

  bool isVideo() {
    return type == "02";
  }

  bool is3DLink() {
    return type == "03";
  }

  bool isDefault() {
    return type == "-1";
  }


  SmartHomeUploadItemBean({
    this.folderName,
    this.picid,
    this.backup,
    this.picsize,
    this.picstorage,
    this.netUrl,
    this.linkUrl,
    this.linkCover,
    this.localUrl,
    this.shid,
    this.sfid,
    this.stid,
    this.scid,
    this.style,
    this.stidName,
    this.scidName,
    this.styleName,
    this.type,
    this.videotime,
    this.videoNetCover,
    this.videoLocalCover,
    this.videoid,
    this.sdVideo,
    this.sdStorage,
    this.videoDuration,
    this.folderWidth,
    this.folderHeight,
    this.folderStorage,
    this.sortIndex,
    this.sysmid,
  });

  ///上传状态
  UploadStatus _status;

  UploadStatus get status => _status;

  set status(UploadStatus value) {
    _status = value;
  }

  ///进度
  double _progress;

  double get progress => _progress;

  set progress(double value) {
    _progress = value;
  }


  ///上传id
  String _id;
  String get id => _id;

  set id(String value) {
    _id = value;
  }


}

enum UploadStatus { start, stop, onProgress, error }
